<template>
	<div class="main-home">
		<!--		<h2>user</h2>-->
		<div  class="main-search">
			<h1>数据大屏</h1>
			<el-form v-if="false" :model="data.searchForm" label-width="auto" inline style="text-align: left;">
				<el-form-item label="账号">
					<el-input v-model="data.searchForm.userAccount" clearable style="width: 200px"
					          @blur="handleSearchClick"/>
				</el-form-item>
				<el-form-item label="名称">
					<el-input v-model="data.searchForm.username" clearable style="width: 200px"
					          @blur="handleSearchClick"/>
				</el-form-item>
				<el-form-item label="邮箱">
					<el-input v-model="data.searchForm.email" clearable style="width: 200px"
					          @blur="handleSearchClick"/>
				</el-form-item>
				<el-form-item label="电话">
					<el-input v-model="data.searchForm.phone" clearable style="width: 200px"
					          @blur="handleSearchClick"/>
				</el-form-item>
				<!--
									<el-form-item label="状态">
										<el-select v-model="data.searchForm.deptState" clearable placeholder="&#45;&#45;请选择&#45;&#45;"
												   style="width: 240px">
											<el-option label="正常" value="0"/>
											<el-option label="禁用" value="1"/>
										</el-select>
									</el-form-item>
				-->
				<el-form-item label="">
					<el-button icon="Search" type="primary" @click="handleSearchClick" round plain>搜索</el-button>
					<el-button icon="Refresh" @click="resetSearchClick" round plain>重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!--有数据-->
		<div v-if="false">
			<!--数据列表-->
			<div class="main-content">
				<h2 style="margin-bottom: 2vw">用户列表</h2>
				<div class="main-content-btn">
					<el-button type="primary" @click="handleAddClick()">新增用户</el-button>
					<el-popconfirm class="box-item" width="450"
					               title="这将选中菜单删除，确定继续？【删除后将无法恢复，请谨慎操作】"
					               icon="" placement="top" confirm-button-type="danger" confirm-button-text="删除"
					               @confirm="handleDeleteList()" persistent>
						<template #reference>
							<el-button type="danger">批量删除</el-button>
						</template>
						<template #actions="{ confirm, cancel }">
							<div class="btn-group" style="text-align: center">
								<el-button size="small" @click="cancel">取消</el-button>
								<el-button type="danger" size="small" @click="confirm">删除</el-button>
							</div>
						</template>
					</el-popconfirm>
				</div>
				<el-table :data="data.list" @selection-change="handleDeleteListClick" highlight-current-row stripe
				          style="width: 100%;">
					<el-table-column type="selection" width="55"/>
					<el-table-column prop="userAccount" label="账号" width="150" sortable show-overflow-tooltip/>
					<el-table-column prop="username" label="名称" width="120" sortable show-overflow-tooltip/>
					<el-table-column prop="password" label="密码" width="100">
						<el-button type="warning" plain size="small">重置密码</el-button>
					</el-table-column>
					<el-table-column prop="avatarUrl" label="头像" width="100">
						<template #default="scope">
							<el-avatar :src="scope.row.avatarUrl"/>
						</template>
					</el-table-column>
					<el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip/>
					<el-table-column prop="phone" label="电话" width="120" sortable/>
					<el-table-column prop="deptName" label="部门" width="120">
						<template #default="scope">
							<el-tag v-show="scope.row.roleName" type="primary" effect="plain">
								{{ scope.row.deptName }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="roleName" label="角色名称" width="120">
						<template #default="scope">
							<el-tag v-show="scope.row.roleName" type="primary" effect="plain">{{ scope.row.roleName }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="roleType" label="角色类型" width="120">
						<template #default="scope">
							<el-tag v-if="scope.row.roleType===roleType[0].name" type="primary" effect="plain"
							        disable-transitions>超级管理员
							</el-tag>
							<el-tag v-else-if="scope.row.roleType===roleType[1].name" type="warning" effect="plain"
							        disable-transitions>管理员
							</el-tag>
							<el-tag v-else-if="scope.row.roleType===roleType[2].name" type="danger" effect="plain"
							        disable-transitions>普通用户
							</el-tag>
							<el-tag v-else type="danger" disable-transitions>未知</el-tag>
						</template>
						<!--						<el-tag type="primary" effect="plain">测试角色</el-tag>-->
					</el-table-column>
					<el-table-column prop="lastLoginIp" label="最近登录IP" width="120"/>
					<el-table-column prop="createTime" label="注册时间" width="180" sortable align="center"/>
					<el-table-column prop="updateTime" label="更新时间" width="180" sortable align="center"/>
					
					
					<!--
										<el-table-column prop="roleType" label="用户类型" width="120">
											<template #default="scope">
												<el-tag v-if="scope.row.roleType==='0'" type="primary" effect="plain" disable-transitions>
													超级管理员
												</el-tag>
												<el-tag v-else-if="scope.row.roleType==='1'" type="warning" effect="plain"
														disable-transitions>管理员
												</el-tag>
												<el-tag v-else-if="scope.row.roleType==='2'" type="danger" effect="plain"
														disable-transitions>普通用户
												</el-tag>
												<el-tag v-else type="danger" disable-transitions>按钮</el-tag>
											</template>
										</el-table-column>
										<el-table-column prop="permissions" label="角色权限" width="80" align="center"/>
										<el-table-column prop="remark" label="角色描述" width="180" align="center" show-overflow-tooltip/>
										<el-table-column prop="createBy" label="创建人" width="180" align="center"/>
					-->
					<el-table-column label="操作" align="center" width="150" fixed="right">
						<template #default="scope">
							<div style="text-align: center">
								<el-button size="small" type="warning" plain
								           @click="handleEditClick(scope.$index, scope.row)">编辑
								</el-button>
								<el-popconfirm class="box-item" width="180"
								               :title="'确定删除 【'+scope.row.userAccount+'】 ？'"
								               icon="" placement="top" confirm-button-type="danger"
								               confirm-button-text="删除"
								               @confirm="handleDelete(scope.$index, scope.row)"
								               persistent>
									<template #reference>
										<!--									@click="handleDelete(scope.$index, scope.row)"-->
										<el-button size="small" type="danger" plain>删除</el-button>
									</template>
									<template #actions="{ confirm, cancel }">
										<div class="btn-group" style="text-align: center">
											<el-button size="small" @click="cancel">取消</el-button>
											<el-button type="danger" size="small" @click="confirm">删除</el-button>
										</div>
									</template>
								</el-popconfirm>
							</div>
						</template>
					</el-table-column>
				</el-table>
				
				<div class="main-content-pagination">
					<el-pagination style="justify-content: center; margin-top: 5vh"
					               v-model:current-page="data.searchForm.current"
					               v-model:page-size="data.searchForm.size"
					               :page-sizes="[10, 30, 50, 100]"
					               layout="total, sizes, prev, pager, next, jumper"
					               :total="data.searchForm.total"
					               @size-change="handleSizeChange"
					               @current-change="handleCurrentChange"
					/>
				</div>
			</div>
			
			<!--新增/修改 对话框-->
			<div class="main-dialog">
				<el-dialog v-model="data.dialog.visible" :title="data.dialog.title" center align-center draggable
				           overflow :show-close="false" width="40vw" @open="handleDialogOpened"
				           :before-close="handleClose">
					<div class="dialog-wrap" style="margin: 20px">
						<el-form :model="data.editForm">
							<el-form-item label="账号" label-width="100">
								<el-input v-model="data.editForm.userAccount" size="large"/>
							</el-form-item>
							<el-form-item :label="data.dialog.name" label-width="100">
								<el-input v-model="data.editForm.username" size="large"/>
							</el-form-item>
							<el-form-item label="邮箱" label-width="100">
								<el-input v-model="data.editForm.email" size="large"/>
							</el-form-item>
							<el-form-item label="电话" label-width="100">
								<el-input v-model="data.editForm.phone" size="large"/>
							</el-form-item>
							<el-form-item label="部门" label-width="100">
								<el-tree-select v-model="data.editForm.deptId" node-key="deptId" :data="data.deptList"
								                :props="defaultProps" @check="handleCheckChange"
								                placeholder="-- 请选择 --" accordion size="large" style="width: 100%;"
								                :render-after-expand="false"/>
							</el-form-item>
							<el-form-item label="角色" label-width="100">
								<el-select v-model="data.editForm.roleId" placeholder="-- 请选择 --" size="large"
								           style="width: 100%">
									<el-option v-for="item in data.roleList" :key="item.value" :label="item.label"
									           :value="item.value"/>
								</el-select>
							</el-form-item>
							<el-form-item label="头像" label-width="100">
								<el-upload
										class="avatar-uploader" :action="data.uploadUrl" :headers="data.headers"
										:before-upload="beforeAvatarUpload"
										:on-success="handleAvatarSuccess"
										:on-error="handleAvatarError"
										:show-file-list="false" style="width: 100%"
								>
									<img v-if="data.editForm.avatarUrl" :src="data.editForm.avatarUrl" class="avatar"/>
									<el-icon v-else class="avatar-uploader-icon">
										<Plus/>
									</el-icon>
								</el-upload>
								<!--
																<el-upload
																		class="avatar-uploader"
																		action="http://47.112.114.52:80/file/upload/"
																		:headers="data.headers"
																		:show-file-list="false"
																		:before-upload="beforeAvatarUpload"
																		:on-success="handleAvatarSuccess"
																		:on-error="handleAvatarError">
																	值：{{ data.editForm.avatarUrl }}
																	<el-avatar v-if="data.editForm.avatarUrl" :src="data.editForm.avatarUrl"
																			   :size="80"></el-avatar>
																	<i v-else class="el-icon-plus avatar-uploader-icon"
																	   style="border: 1px dashed #d9d9d9;padding: 50px;"></i>
																	&lt;!&ndash;									   style="border: 1px dashed #d9d9d9;padding: 50px;"></i>&ndash;&gt;
																	<div>只支持jpg</div>
																</el-upload>
								-->
							</el-form-item>
						</el-form>
					</div>
					<template #footer>
						<div class="dialog-footer">
							<el-button @click="handleClose()" style="margin-right: 5vw">取消</el-button>
							<el-button v-if="data.dialog.btnName=='新增'" type="primary"
							           @click="addData">新增
							</el-button>
							<el-button v-else type="warning" @click="editData">编辑
							</el-button>
						</div>
					</template>
				</el-dialog>
				<!--删除 对话框-->
				<el-dialog v-model="data.deleteDialog.visible" title="警告" center align-center draggable overflow
				           :show-close="false" width="30vw" :before-close="handleDeleteClose">
					<h3 style="color: red; text-align: center;">该操作会删除【{{ data.deleteDialog.deleteName }}】下的所有数据！<br>请谨慎操作！<br>
					</h3>
					<p style="text-align: center; margin:3vh auto 5vh auto">是否继续？</p>
					<div class="dialog-footer" style="text-align: center">
						<el-button @click="data.deleteDialog.visible=false; infoMessage(true,'已取消')"
						           style="margin-right: 5vw">取消
						</el-button>
						<el-button type="danger" @click="data.deleteDialog.visible=false; handleDeleteForTreeId()">删除
						</el-button>
					</div>
				</el-dialog>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { reqList, reqAdd, reqDelete, reqDeleteList, reqEdit } from '@/service/main/user.ts'
import { errorMessage, infoMessage, successMessage } from '@/utils/ElMessageUtils.ts'
import { reactive, ref } from 'vue'
import { reqGetDeptTree } from '@/service/main/dept.ts'
import { BASE_URL } from '@/service/config'
import { LocalStorageUtils } from '@/utils/StorageUtils.ts'

/********************************************* 变量区 ************************************************************/
// 部门树。
const defaultProps = {
	children: 'children',
	label: 'deptName'
}

// 角色类型
const roleType = [
	{ code: '0', name: 'SUPER_ADMIN' },
	{ code: '1', name: 'ADMIN' },
	{ code: '2', name: 'USER' }
]


const treeRef = ref()

// 数据内容。
let data = reactive({
	dialog: {
		visible: false,
		title: '新增用户',
		isAdd: false,   // 是否添加。
		name: '',// 名称
		btnName: ''
	},
	deleteDialog: {
		visible: false,
		deptId: '',
		deleteName: ''
	},
	// 搜索条件。
	searchForm: {},
	uploadUrl: BASE_URL + '/file/upload/',
	// 添加/编辑表单。
	editForm: {},
	// 上传头像所需要的token。
	headers: { token: LocalStorageUtils.getKey('wisdomToken') },
	deleteList: [],
	// 列表展示内容。
	list: [],
	// 菜单列表。
	menuList: [],
	// 部门列表。
	deptList: [],
	// 角色列表。
	roleList: [{
		value: '0',
		label: '超级管理员'
	}, {
		value: '1',
		label: '管理员'
	}, {
		value: '2',
		label: '普通用户'
	}]
})

/********************************************* API接口 ************************************************************/
// 获取菜单。
const dataList = function getList(searchData = null) {
	reqList(searchData).then(res => {
		console.log('reqList.res ====> ', res)
		if (res.resultStatus) {
			data.list = res.resultData.records
		} else {
			errorMessage(true, '动态菜单获取失败！！')
		}
	})
}
dataList()

// 获取角色。
const getList = function getDeptList(searchData = null) {
	reqGetDeptTree(searchData).then(res => {
		console.log('reqGetDeptTree.res ====> ', res)
		if (res.resultStatus) {
			data.deptList = res.resultData
		} else {
			errorMessage(true, '动态菜单获取失败！！')
		}
	})
}
getList()

// 搜索框。
function handleSearchClick() {
	// console.log('搜索数据：：：：：', data.searchForm)
	dataList(data.searchForm)
}

// 添加数据。
function addData() {
	// console.log('data.editForm =========> ', data.editForm)
	reqAdd(data.editForm).then(res => {
		if (res.resultStatus) {
			console.log('reqAdd.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
			data.dialog.visible = false
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
	// handleSearchClick()
}

// 修改数据。
function editData() {
	reqEdit(data.editForm).then(res => {
		if (res.resultStatus) {
			console.log('reqEdit.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
			data.dialog.visible = false
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
}

/**
 * 单条删除。
 * @param type
 * @param index
 * @param row
 */
function handleDelete(index, row) {
	console.log('handleDelete.row =====>  ', row)
	reqDelete(row.userId).then(res => {
		if (res.resultStatus) {
			console.log('reqDelete.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
}

// 批量删除。
function handleDeleteList() {
	let idList = {
		idList: []
	}
	data.deleteList.forEach((item) => {
		console.log('item ====>', item)
		idList.idList.push(item.userId)
	})
	// console.log("ids =====>",ids)
	reqDeleteList(idList).then(res => {
		if (res.resultStatus) {
			console.log('reqDeleteList.res!', res)
			successMessage(true, res.resultData)
			dataList()
			formClear()
		} else {
			errorMessage(true, res.errorMessage)
		}
	})
}

/********************************************* 事件 ************************************************************/

// 重置搜索框。
function resetSearchClick() {
	data.searchForm = {}
	handleSearchClick()
}

/**
 * 添加。
 * @param type
 * @param index
 * @param row
 */
function handleAddClick() {
	data.dialog = {
		visible: true,
		title: '新增用户',
		isAdd: true,
		name: '名称',
		btnName: '新增'
	}
}

/**
 * 编辑。
 * @param type
 * @param index
 * @param row
 */
function handleEditClick(index = null, row) {
	data.dialog = {
		visible: true,
		title: '编辑用户',
		isAdd: true,
		name: '名称',
		btnName: '编辑'
	}
	console.log('row =====> ', row)
	// 遍历选择。
	data.editForm = row
}

/**
 * 批量删除。
 */
function handleDeleteListClick(newSelection) {
	data.deleteList = newSelection
	console.log('newSelection ====>', newSelection)
	console.log('批量删除！')
}

// 选择选中。
const handleCheckChange = (data, selectData) => {
	// console.log('selectData.checkedKeys ====> ', selectData.checkedKeys)
	setCheckedKeys(selectData.checkedKeys)
}

// 弹窗显示后，显示选中的菜单权限。
const handleDialogOpened = () => {
	// console.log('data.editForm.menuPermissions  ==> ', data.editForm.menuPermissions)
	if (data.editForm.menuPermissions) {
		setCheckedKeys(data.editForm.menuPermissions)
	}
}


const handleSizeChange = (val) => {
	// console.log(`每页 ${val} 条`);
	this.data.searchForm.size = val
	this.dataList()
}
const handleCurrentChange = (val) => {
	// console.log(`当前页: ${val}`);
	this.data.searchForm.current = val
	this.dataList()
}

/*-------------------------------------------- start：头像相关函数【文件上传】 -----------------------------------------------*/
// 修改头像图标。
function updateAvatarUrl() {
	// 修改用户头像API接口。
	
	// console.log("修改手机号！！")
	// this.$store.dispatch('updateAvatarUrl', this.userInfo.avatarUrl).then(res => {
	// 	// console.log("updatePhone.res", res);
	// 	if (res !== undefined && res.resultStatus === true) {
	// 		this.$message.success(res.resultData);
	// 		this.getUserInfo()
	// 	}
	// })
}

// 文件上传成功时的钩子。
function handleAvatarSuccess(res, file) {
	// console.log("上传成功！保存头像路径！。。。。")
	// this.imageUrl = URL.createObjectURL(file.raw);
	// console.log("imageUrl ==============>",this.imageUrl);
	// console.log("res ===>",res);
	// console.log("file ===========>",file);
	if (res !== undefined && res.resultStatus === true) {
		data.editForm.avatarUrl = res.resultData
	}
	updateAvatarUrl()  // 调用API接口。
	
}

function handleAvatarError(err, file) {
	// console.log("头像上传失败！",err)
	errorMessage(true, '头像上传失败！' + err)
}

// 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
/**
 * 只能上传 jpg 格式图片，且文件大小 < 2MB！
 * @param file
 */
function beforeAvatarUpload(file) {
	// console.log("file ===> ",file);
	const isJPG = file.type === 'image/jpeg'
	const isLt2M = file.size / 1024 / 1024 < 2
	// console.log("上传头像。。。。")
	if (!isJPG) {
		errorMessage(true, '上传头像图片只能是 JPG 格式!')
	} else if (!isLt2M) {
		errorMessage(true, '上传头像图片大小不能超过 2MB!')
	}
	return isJPG && isLt2M
	// return false
}

// // 获取头像token。
// function getAvatarToken() {
// 	console.log('token =======> ', LocalStorageUtils.getKey('wisdomToken'))
// 	data.headers =
// }
//
// getAvatarToken()
/*-------------------------------------------- end：头像相关函数【文件上传】 -----------------------------------------------*/

/********************************************* tree选中数据 ************************************************************/
// 设置值。
const setCheckedKeys = (data) => {
	treeRef.value!.setCheckedKeys(data, false)
}
const getCheckedKeys = () => {
	return treeRef.value!.getCheckedKeys(false)
}
// 重置值。
const resetChecked = () => {
	if (treeRef.value) {
		treeRef.value!.setCheckedKeys([], false)
	}
}

/********************************************* 初始化数据 ************************************************************/
// 清除垃圾数据。
function formClear() {
	data.editForm = {}
	data.dialog = {
		visible: false,
		title: '',
		isAdd: false,
		name: '',
		btnName: '新增'
	}
	resetChecked()
}

// 关闭新增/修改弹窗。
function handleClose() {
	formClear()
	infoMessage(true, '已取消')
}

// 关闭删除弹窗。
function handleDeleteClose() {
	data.deleteDialog.visible = false
	infoMessage(true, '已取消')
}
</script>

<style scoped lang="less">
.main-search {
	background-color: white;
	margin-bottom: 20px;
	padding: 5vh 0 2vh 5vw;
	border-radius: 10px;
}

.main-content {
	background-color: white;
	padding: 20px;
	border-radius: 10px;
}

.main-content-btn {
	margin-bottom: 20px;
}

.main-content-pagination {
	display: block;
	text-align: center;
	width: 100%;
}

:global(.el-popconfirm__main) {
	color: red;
	text-align: center;
	white-space: pre-line;
}


.icon-list {
	display: inline-block;
	width: 35px;
	height: 35px;
}

.select-option {
	display: inline-block;
}

/************************************************ start：头像样式 *************************************************/
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}

.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	border: 2px dashed #d9d9d9;
	width: 178px;
	height: 178px;
	text-align: center;
}

/************************************************ end：头像样式 *************************************************/
</style>